package fi.iki.juri.units;

/**
 * A Converter executes a sequence of Calculators to get from one Unit to another.
 * 
 * @author Juri Pakaste <juri@iki.fi>
 */
public class Converter {
	private final Conversion head;
	private final Converter tail;

	public Converter(final Conversion head, final Converter tail) {
		this.head = head;
		this.tail = tail;
	}

	public Conversion getHead() {
		return head;
	}

	public Converter getTail() {
		return tail;
	}
	
	public boolean hasConverter(final Unit converter) {
		return head.getUnit().equals(converter) || (tail != null && tail.hasConverter(converter));
	}
	
	public String toString() {
		return String.format("(%1$s %2$s %3$s)", head.getUnit().getName(), head.getCalculation(), tail != null ? tail.toString() : "()");
	}

	public double convert(final double value) {
		return head.getCalculation().perform(tail != null ? tail.convert(value) : value);
	}
}
